#ifndef TASK_H
#define TASK_H

#include "comm/types.h"
#include "cpu/cpu.h"
#include "tools/list.h"
#include "fs/file.h"

#define TASK_NAME_SIZE 32
#define TASK_TIME_SLICE_DEFAULT 10
#define TASK_OFILE_NR       128

#define TASK_FLAG_SYSTEM        (1<<0)

typedef struct _task_args_t
{
    uint32_t ret_addr;
    uint32_t argc;
    char** argv;
}task_args_t;


typedef struct _task_t
{
    enum{
        TASK_CREATED,
        TASK_RUNNING,
        TASK_SLEEP,
        TASK_READY,
        TASK_WAITTING,
        TASK_ZOMBIE,
    } state;

    char name[TASK_NAME_SIZE];

    int pid;
    struct _task_t* parent;

    uint32_t heap_start;
    uint32_t heap_end;

    int sleep_ticks;    //进程睡眠时间
    int time_ticks;     //任务所能占用的cpu时间片的最大时间(时钟中断次数)
    int slice_ticks;    //每次时钟中断就减一,初始和time_ticks值相同

    int status;

    file_t* file_table[TASK_OFILE_NR];

    tss_t tss;  //任务段描述符
    int tss_seg;    //tss选择子

    list_node_t run_node;
    list_node_t wait_node;
    list_node_t all_node;
}task_t;

int task_init(task_t * task,const char * task_name, int flag, uint32_t entry,uint32_t esp);
void task_switch_from_to(task_t * from,task_t *to);
void task_set_ready(task_t * task);
void task_set_block(task_t * task);
void task_time_tick();

file_t* task_file(int fd);
int task_alloc_fd(file_t* file);
void task_remove_fd(int fd);

//定义任务管理器
typedef struct _task_manager_t
{
    task_t * curr_task;

    list_t ready_list;
    list_t task_list;
    list_t sleep_list;

    task_t first_task;
    task_t idle_task;

    int app_code_seg;
    int app_data_seg;
}task_manager_t;

void task_manager_init();
void task_first_init();
task_t * task_first_task();

int sys_sched_yield();
void sys_exit(int status);
int sys_wait(int* status);

void task_dispatch();
task_t * task_current();

void task_set_sleep(task_t * task,uint32_t ticks);
void task_set_wakeup(task_t * task);

void sys_sleep(uint32_t  ms);
int sys_getpid();
int sys_fork();
int sys_execve(char * name,char **argv,char** env);

#endif